import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/',
  //   name: 'Home',
  //   component: Home
  // },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login/index.vue') // 路由懒加载  注释表示打包分类
  },
  {
    path: '/reg',
    name: 'register',
    component: () => import('../views/Reg/index.vue') // 路由懒加载  注释表示打包分类
  },

  /* 首页入口 */
  /*
  如果二级路由写了 /  就不需要根据一级路由来查找
  如果二级路由没有写 /  需要根据一级路由来进行拼接查找
   */
  {
    path: '/',
    component: () => import('../views/layout/index.vue'),
    children: [
      { path: '', component: () => import('../views/Home/index.vue') },
      {
        path: 'artCategory',
        component: () => import('../views/art/artCategory.vue')
      },
      { path: 'artList', component: () => import('../views/art/artList.vue') },
      {
        path: 'userInfo',
        component: () => import('../views/user/userInfo.vue')
      },
      {
        path: 'changeAvatar',
        component: () => import('../views/user/changeAvatar.vue')
      },
      {
        path: 'resetPwd',
        component: () => import('../views/user/resetPwd.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})


/*
路由拦截：只要路由值发生改变就会触发
请求拦截：只要发送请求就会触发
 */
router.beforeEach((to, from, next) => {
  // debugger
  console.log(to.path, 6667777) //  断点调试
  //  to=》去哪里   from=>从哪里来   next =>  放行   函数
  /*
  + login +  reg 可以直接访问
  + 其他页面要访问必须要有token
   */
  var whiteList = ['/login', '/reg']
  console.log(to.path, whiteList.includes(to.path), 89)
  if (whiteList.includes(to.path)) {
    //  存在
    next()
  } else {
    //  判断是否有token
    if (localStorage.getItem('token')) {
      next()
    } else {
      //  表示既没有token访问的也不是 whiteList  中的
      next('/login')
    }
  }
})

export default router
